"""
The MIT License (MIT)
Copyright © 2022 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-esp32-walkie-talkie
"""

'''
| MAX98357A | ESP32 |
|-------------------|
|   LRC <===> IO13  |
|  BCLK <===> IO14  |
|   DIN <===> IO12  |
|   GND <===> GND   |
|   Vin <===> VIN   |
'''
from machine import Pin, I2S

BUFF_SIZE = 2000
WAVE_SAMPLES_MV = memoryview(bytearray(BUFF_SIZE))

# wave file
WAVE_FILE = 'pcm/tone1_bits16_rate16000_mono.wav'
BITS = 16
FORMAT = I2S.MONO
RATE = 16000

class Pins(object):
	BUTTON = 0

	DIN = SD = Pin(12)
	BCLK = SCK = Pin(14)
	LRCLK = WS = Pin(13)


class MAX98357(object):
	def __init__(self):
		self.__audio = I2S(
			1,
			sck=Pins.SCK, 
			ws=Pins.WS,
			sd=Pins.SD,
			mode=I2S.TX,
			bits=BITS,
			format=FORMAT,
			rate=RATE,
			ibuf=BUFF_SIZE
		)

		self.__button = Pin(Pins.BUTTON, Pin.IN)
		self.__button.irq(self.__button_irq, Pin.IRQ_RISING)

	def __button_irq(self, pin_instance):
		with open(WAVE_FILE, 'rb') as file:
			file.seek(44) # skip wave header
			read_count = file.readinto(WAVE_SAMPLES_MV)

			while read_count > 0:
				print(self.__audio.write(WAVE_SAMPLES_MV[0:read_count]))
				read_count = file.readinto(WAVE_SAMPLES_MV)

		print('done')


def main():
	MAX98357()


if __name__ == '__main__':
	main()
